package down;

import android.content.Context;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.SpeedCalculator;
import com.liulishuo.okdownload.core.Util;
import com.liulishuo.okdownload.core.breakpoint.BlockInfo;
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.listener.DownloadListener4WithSpeed;
import com.liulishuo.okdownload.core.listener.assist.Listener4SpeedAssistExtend;

import java.util.List;
import java.util.Map;

import download_temp.FileInfo;
import download_temp.view.NumberProgressBar;

public class MyDownloadListener4WithSpeed extends DownloadListener4WithSpeed {
    private FileInfo itemInfo;
    private long totalLength;
    private String readableTotalLength;

    private TextView speed;
    private NumberProgressBar progressBar;//谨防内存泄漏
    private Context context;//谨防内存泄漏

    private DownLoaderHelper helper;


    public interface DownSuccessCallback {
        void success(FileInfo fileInfo);
    }

    private DownSuccessCallback callback;


    public void setCallback(DownSuccessCallback callback) {
        this.callback = callback;
    }

    public MyDownloadListener4WithSpeed(FileInfo itemInfo, NumberProgressBar progressBar, TextView speed) {
        this.itemInfo = itemInfo;
        this.progressBar = progressBar;
        this.speed = speed;
        this.context = progressBar.getContext();
        helper = new DownLoaderHelper(context);
    }

    @Override
    public void taskStart(@NonNull DownloadTask task) {
//        Log.i("bqt", "【1、taskStart】");
        updateState("开始下载");
    }

    @Override
    public void infoReady(@NonNull DownloadTask task, @NonNull BreakpointInfo info, boolean fromBreakpoint, @NonNull Listener4SpeedAssistExtend.Listener4SpeedModel model) {
        totalLength = info.getTotalLength();
        readableTotalLength = Util.humanReadableBytes(totalLength, true);
//        Log.i("bqt", "【2、infoReady】当前进度" + (float) info.getTotalOffset() / totalLength * 100 + "%" + "，" + info.toString());
        itemInfo.setLength((int) totalLength);
        helper.updateData(helper.getWritableDatabase(), itemInfo);
    }

    @Override
    public void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaders) {
//        Log.i("bqt", "【3、connectStart】" + blockIndex);
    }

    @Override
    public void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaders) {
//        Log.i("bqt", "【4、connectEnd】" + blockIndex + "，" + responseCode);
    }

    @Override
    public void progressBlock(@NonNull DownloadTask task, int blockIndex, long currentBlockOffset, @NonNull SpeedCalculator blockSpeed) {
//        Log.i("bqt", "【5、progressBlock】" + blockIndex + "，" + currentBlockOffset);
    }

    @Override
    public void progress(@NonNull DownloadTask task, long currentOffset, @NonNull SpeedCalculator taskSpeed) {
        String readableOffset = Util.humanReadableBytes(currentOffset, true);
        String progressStatus = readableOffset + "/" + readableTotalLength;
        String speed = taskSpeed.speed();
        float percent = (float) currentOffset / totalLength * 100;
//        Log.i("bqt", "【6、progress】" + currentOffset + "[" + progressStatus + "]，速度：" + speed + "，进度：" + percent + "%");
        updateState(progressStatus);
//        updateState(speed);
        itemInfo.setFinished(currentOffset);
        progressBar.setProgress((int) percent);
    }

    @Override
    public void blockEnd(@NonNull DownloadTask task, int blockIndex, BlockInfo info, @NonNull SpeedCalculator blockSpeed) {
//        Log.i("bqt", "【7、blockEnd】" + blockIndex);
    }

    @Override
    public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause, @NonNull SpeedCalculator taskSpeed) {
//        Log.i("bqt", "【8、taskEnd】" + cause.name() + "：" + (realCause != null ? realCause.getMessage() : "无异常"));
        if (cause == EndCause.COMPLETED) {
            updateState("下载完成");
            itemInfo.status = 3; //修改状态
            callback.success(itemInfo);
            helper.updateData(helper.getWritableDatabase(), itemInfo);
        } else {
            itemInfo.status = 2; //修改状态
            if (cause == EndCause.CANCELED) {
                updateState("下载暂停");
                helper.updateData(helper.getWritableDatabase(), itemInfo);
            } else if (cause == EndCause.ERROR) {
//                updateState("任务出错");
            } else if (cause == EndCause.FILE_BUSY || cause == EndCause.SAME_TASK_BUSY || cause == EndCause.PRE_ALLOCATE_FAILED) {
                updateState(cause.name());
            }
        }
    }
    private void updateState(String state) {
        this.speed.setText(state);
    }
}